package deployr.core;

import java.io.*;
import java.math.*;
import java.security.*;

public class Checksums {

	public static final MessageDigest usingMd5() {
		try {
			return MessageDigest.getInstance("MD5");
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public static final MessageDigest usingSha1() {
		try {
			return MessageDigest.getInstance("SHA1");
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public static final String md5(File file) {
		return apply(usingMd5(), file);
	}

	public static final String sha1(File file) {
		return apply(usingSha1(), file);
	}

	public static final String sha1(byte[] bytes) {
		return apply(usingSha1(), new ByteArrayInputStream(bytes));
	}

	private static String apply(MessageDigest digest, File file) {
		return apply(digest, openStreamOn(file));
	}

	private static String apply(MessageDigest md5, InputStream inputStream) {
		try {
			final byte[] buf = new byte[8192];
			int len;
			while ((len = inputStream.read(buf)) > 0) {
				md5.update(buf, 0, len);
			}
			inputStream.close();
			return new BigInteger(1, md5.digest()).toString(16);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	public static final String md5(String string) {
		try {
			return apply(usingMd5(), new ByteArrayInputStream(string.getBytes("utf8")));
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}

	private static final FileInputStream openStreamOn(File file) {
		try {
			return new FileInputStream(file);
		} catch (Exception e) {
			throw new RuntimeException("unable to open stream " + file.getAbsolutePath(), e);
		}
	}
}
